package com.monitor.util;

import com.monitor.constant.URIPatternConstant;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Set;

@Component
public class URLPatternUtil {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public String lookupBestURL(String url) {
        // 获取配置的URIPattern
        Object o = SimpleCache.getSimpleCache().get(URIPatternConstant.URI_PATTERN);
        Set<String> uriPatterns = (Set<String>) o;
        // 完全匹配
        if (uriPatterns.stream().anyMatch(uriPattern -> uriPattern.equals(url))) {
            return uriPatterns.stream().filter(uriPattern -> uriPattern.equals(url)).findFirst().orElse("");
        } else {
            // pattern匹配
            return uriPatterns.stream().filter(uriPattern -> antPathMatcher.match(uriPattern, url)).min(antPathMatcher.getPatternComparator(url)).orElse("");
        }
    }

}
